<?php

class Provider_Connector
{
    protected $content_type = array('text/xml', 'application/xml', 'text/json', 'application/json', 'application/atom+xml');

    public function checkUrlvalid($id)
    {
        $connector = new Connector();
        if (!$id || !$connector->get($id)) {
            return _MSG_INVALID_PARAMETER;
        }
        
        $session = curl_init($connector->URL);
        curl_setopt($session, CURLOPT_HEADER, FALSE);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($session, CURLOPT_CONNECTTIMEOUT, 1800);
        $response = curl_exec($session);
        $content_type = curl_getinfo($session, CURLINFO_CONTENT_TYPE);
        preg_match( '@([-\w/+]+)(;\s+charset=(\S+))?@i', $content_type, $matches);  
        if (!$matches || !isset($matches[1]) || !in_array($matches[1], $this->content_type)) {
            return _MSG_INVALID_FORMAT_XML;
        }
        curl_close($session);
        
        if ($matches[1] == $this->content_type[0] || $matches[1] == $this->content_type[1] || $matches[1] == $this->content_type[4]) {
            if ($connector->CLASS_NAME == 'AggregateDealTipToken') {
                $response = str_replace(array("<description>", "</description>", "<restrictions>", "</restrictions>", "<highlights>", "</highlights>", "<details>", "</details>","<fine_print>", "</fine_print>"), array("<description><![CDATA[", "]]></description>", "<restrictions><![CDATA[", "]]></restrictions>", "<highlights><![CDATA[", "]]></highlights>", "<details><![CDATA[", "]]></details>", "<fine_print><![CDATA[", "]]></fine_print>"), $response);
            }

            if ($connector->CLASS_NAME == 'AggregateDealLivingSocial') {
                $response = str_replace(array('xmlns="http://www.w3.org/2005/Atom"', 'xml:lang="en-US"', 'xmlns:ls="http://livingsocial.com/ns/1.0"', 'xmlns:georss="http://www.georss.org/georss"', '<georss:', '</georss:', '<ls:', '</ls:'), array("", "", "", "", "<", "</", "<", "</"), $response);
            }

            $xml = @simplexml_load_string($response, null, LIBXML_NOCDATA);
            $datas = @json_decode(@json_encode($xml),1);
        } else {
            $datas = @json_decode($response,1);
        }
        
        if (!self::isValidateXML($datas, $connector->CLASS_NAME)) {
            return _MSG_INVALID_FORMAT_XML;
        }
        
        return _MSG_CONNECTOR_URL_IS_VALID_ONE;
    }
    
     public function isValidateXML($datas, $class_name) {
        if ($class_name == 'AggregateDealTipToken') {
            if (!isset($datas['@attributes']['message']) || $datas['@attributes']['message'] != 'OK') return false;
            if (!isset($datas['deals']['deal'])) return false;
            foreach ($datas['deals']['deal'] as $key=>$deal)
            {
                if (!isset($deal['id'])) return false;
                if (!isset($deal['isocountry'])) return false;
                if (!isset($deal['language'])) return false;
                if (!isset($deal['longitude'])) return false;
                if (!isset($deal['category'])) return false;
                if (!isset($deal['title'])) return false;
                if (!isset($deal['highlights'])) return false;
                if (!isset($deal['details'])) return false;
                if (!isset($deal['merchant'])) return false;
                if (!isset($deal['address'])) return false;
                if (!isset($deal['city'])) return false;
                if (!isset($deal['zip'])) return false;
                if (!isset($deal['country'])) return false;
                if (!isset($deal['vendor_website_url'])) return false;
                if (!isset($deal['phone'])) return false;
                if (!isset($deal['htcimage'])) return false;
                if (!isset($deal['price'])) return false;
                if (!isset($deal['restrictions'])) return false;
                if (!isset($deal['discount_percent'])) return false;
                if (!isset($deal['conditions'])) return false;
                if (!isset($deal['conditions']['minimum_purchase'])) return false;
                if (!isset($deal['conditions']['maximum_purchase'])) return false;
                if (!isset($deal['REDEEMED_END_DATE'])) return false;
                if (!isset($deal['buyurl'])) return false;
                if (!isset($deal['buttontxt'])) return false;
            }
        } 
        elseif ($class_name == 'AggregateDealBuyWithMe') {
            if (!isset($datas['response']['code']) || $datas['response']['code'] != 'GOOD') return false;
            if (!isset($datas['deal'])) return false;
            foreach ($datas['deal'] as $key=>$deal)
            {
                if (!isset($deal['id'])) return false;
                if (!isset($deal['country'])) return false;
                if (!isset($deal['language'])) return false;
                if (!isset($deal['locations'])) return false;
                if (!isset($deal['category'])) return false;
                if (!isset($deal['subcategory'])) return false;
                if (!isset($deal['title'])) return false;
                if (!isset($deal['short_description'])) return false;
                if (!isset($deal['restrictions'])) return false;
                if (!isset($deal['description'])) return false;
                if (!isset($deal['merchant_name'])) return false;
                if (!isset($deal['web_address'])) return false;
                if (!isset($deal['phone_number'])) return false;
                if (!isset($deal['large_image_url'])) return false;
                if (!isset($deal['packages'])) return false;
                if (!isset($deal['packages']['package'])) return false;
                if (!isset($deal['end_date'])) return false;
                if (!isset($deal['min_number_purchases'])) return false;
                if (!isset($deal['expires_at'])) return false;
                if (!isset($deal['purchase_url'])) return false;
                if (!isset($deal['action'])) return false;
            }
        } 
        else if ($class_name == 'AggregateDealLivingSocial') {
            if (!isset($datas['entry'])) return false;
            foreach ($datas['entry'] as $key=>$deal)
            {
                if (!isset($deal['id'])) return false;
                if (!isset($deal['country_code'])) return false;
                if (!isset($deal['updated'])) return false;
                if (!isset($deal['categories'])) return false;
                if (!isset($deal['subtitle'])) return false;
                if (!isset($deal['description'])) return false;
                if (!isset($deal['merchant_name'])) return false;
                if (!isset($deal['image_url'])) return false;
                if (!isset($deal['content'])) return false;
                if (!isset($deal['price'])) return false;
                if (!isset($deal['details'])) return false;
                if (!isset($deal['savings'])) return false;
                if (!isset($deal['offer_ends_at'])) return false;
                if (!isset($deal['link'])) return false;
                if (!isset($deal['link']['@attributes'])) return false;
                if (!isset($deal['link']['@attributes']['href'])) return false;
        }
        } else {
            if (!isset($datas['@attributes']['message']) || $datas['@attributes']['message'] != 'OK') return false;
            if (!isset($datas['deals']['deal'])) return false;
            foreach ($datas['deals']['deal'] as $key=>$deal)
            {
                if (!isset($deal['id_deal'])) return false;
                if (!isset($deal['country'])) return false;
                if (!isset($deal['language'])) return false;
                if (!isset($deal['language']['@attributes'])) return false;
                if (!isset($deal['language']['@attributes']['id'])) return false;
                if (!isset($deal['categories'])) return false;
                if (!isset($deal['language']['catch_phrase'])) return false;
                if (!isset($deal['language']['short_description'])) return false;
                if (!isset($deal['language']['long_description'])) return false;
                if (!isset($deal['language']['preview_image'])) return false;
                if (!isset($deal['price'])) return false;
                if (!isset($deal['language']['discount_conditions'])) return false;
                if (!isset($deal['savings'])) return false;
                if (!isset($deal['end_date'])) return false;
                if (!$this->validateDateRFC(str_replace('UT', '+0000',$deal['end_date']))) return false;
                if (!isset($deal['conditions']['min_number_purchaser'])) return false;
                if (!isset($deal['conditions']['max_number_purchaser'])) return false;
                if (!isset($deal['conditions']['redeemed_end_date'])) return false;
                if (!isset($deal['language']['purchase_url'])) return false;
                if (!isset($deal['language']['action'])) return false;
                if (isset($deal['merchant'])) {
                    if (!isset($deal['merchant']['merchant_name'])) return false;
                    //if (!isset($deal['merchant']['web_address'])) return false;
                    if (!isset($deal['merchant']['location'])) return false;
                }else{
                    return false;
                }
            }
	}
        return true;
	}  
    
    function validateDateRFC($datetime) {
        $datetime = trim($datetime);
        $pattern1 = "/^([A-Za-z]{3})([\,]) ([0-9]{1,2}) ([A-Za-z]{3}) ([0-9]{2,4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) ([\-+]?)([0-9]{4})$/i";
        $pattern2 = "/^([A-Za-z]{3})([\,]) ([0-9]{1,2}) ([A-Za-z]{3}) ([0-9]{2,4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) UT$/i";
        //strptime($datetime,'%a, %d %b %Y %T %z')
        if(preg_match($pattern1, $datetime) || preg_match($pattern2, $datetime)) {
            return true;
		}
		else {
			return false;
		}
	}
    
    public function getlistClassAggregateVideo($file_dir)
    {
        $dir = opendir ($file_dir);
        $arr_filename = array();
        while (false !== ($filename = readdir($dir))) {
            $info = pathinfo($filename);
            $type = strtolower($info['extension']);
            if($type == 'php'){
                if (preg_match("/AggregateVideo/i", $filename)) {
                    $class_name = substr($filename,0,-4);
                    $arr_filename[$class_name] = $class_name;
                }
            }
        }
        return $arr_filename;
    }
}
